package com.lc.reader.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.lc.reader.data.model.Bookmark
import com.lc.reader.databinding.ItemBookmarkBinding
import java.text.SimpleDateFormat
import java.util.*

class BookmarkAdapter(
    private val onBookmarkClick: (Bookmark) -> Unit
) : ListAdapter<Bookmark, BookmarkAdapter.BookmarkViewHolder>(BookmarkDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookmarkViewHolder {
        val binding = ItemBookmarkBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return BookmarkViewHolder(binding, onBookmarkClick)
    }

    override fun onBindViewHolder(holder: BookmarkViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class BookmarkViewHolder(
        private val binding: ItemBookmarkBinding,
        private val onBookmarkClick: (Bookmark) -> Unit
    ) : RecyclerView.ViewHolder(binding.root) {

        private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())

        fun bind(bookmark: Bookmark) {
            binding.textBookmarkDescription.text = bookmark.description
            binding.textBookmarkPage.text = "第${bookmark.pageNumber + 1}页"
            binding.textBookmarkTime.text = dateFormat.format(Date(bookmark.timestamp))

            binding.root.setOnClickListener { onBookmarkClick(bookmark) }
        }
    }

    private class BookmarkDiffCallback : DiffUtil.ItemCallback<Bookmark>() {
        override fun areItemsTheSame(oldItem: Bookmark, newItem: Bookmark): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: Bookmark, newItem: Bookmark): Boolean {
            return oldItem == newItem
        }
    }
}
